<!-- 
  怎么做一个组件：
    找什么样：html + css
    逻辑：
      1. props
      2. data
      3. events   $emit
      4. slots
      5. expose
 -->

<template>
  <div v-show="list.length > 0" class="history">
    <div class="head">
      <p>搜索历史</p>
      <VanButton size="small" @click="isDel = !isDel">Toggle</VanButton>
    </div>

    <div class="box" :class="{ del: isDel }">
      <div class="item" v-for="item in list" :key="item.cinemaId" @click="onClick(item)">
        <span>{{ item.name }}</span>
        <VanIcon name="cross" color="red" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
const props = withDefaults(
  defineProps<{
    max?: number
  }>(),
  {
    max: 5
  }
)

const defaultList = localStorage.getItem('cinemas-history')

const router = useRouter()

const list = ref<ICinema[]>(defaultList ? JSON.parse(defaultList) : [])
const isDel = ref(false) // 是否删除模式

function add(cinema: ICinema) {
  // 0. 判断不要重复的影院
  if (list.value.find((item) => item.cinemaId === cinema.cinemaId)) {
    return
  }

  // 1. 追加到 list 中
  list.value.unshift(cinema)
  // 2. 控制最大 5条记录
  list.value = list.value.splice(0, props.max)
  // 3. 本地持久化
  localStorage.setItem('cinemas-history', JSON.stringify(list.value))
}

function onClick(cinema: ICinema) {
  if (isDel.value) {
    // 删除模式
    list.value = list.value.filter((item) => item.cinemaId !== cinema.cinemaId)
    localStorage.setItem('cinemas-history', JSON.stringify(list.value))
  } else {
    // 跳转模式
    router.push({ name: 'city' })
  }
}

// 对外暴露
defineExpose({
  add
})
</script>

<style scoped>
.history {
  padding: 20px;
}

.box {
  display: flex;
  flex-wrap: wrap;
}

.item {
  margin-right: 10px;
  margin-bottom: 10px;
  height: 30px;
  background-color: hsla(0, 0%, 95.7%, 0.6);
  line-height: 14px;
  border-radius: 3px;
  box-sizing: border-box;
  font-size: 13px;
  padding: 8px 12px;
}

.van-icon {
  display: none;
}

.del .van-icon {
  display: inline-block;
}

.head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #ccc;
}
</style>
